﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
using OLMS_MVC2.Models; // 请替换为你的模型命名空间

namespace OLMS_MVC2.BLL
{
    public class DataToExcel : IDisposable
    {
        private Excel.Application _excelApp;
        private Excel.Workbook _workbook;
        private bool _disposed = false;

        public DataToExcel()
        {
            _excelApp = new Excel.Application
            {
                Visible = false,
                DisplayAlerts = false
            };
        }

        /// <summary>
        /// 导出订单数据到Excel
        /// </summary>
        public byte[] ExportOrders(List<OrderSummaryViewModel> orders)
        {
            string tempFile = null;
            try
            {
                _workbook = _excelApp.Workbooks.Add();
                Excel.Worksheet worksheet = (Excel.Worksheet)_workbook.ActiveSheet;

                // 简单表头
                worksheet.Cells[1, 1] = "专辑ID";
                worksheet.Cells[1, 2] = "总销量";
                worksheet.Cells[1, 3] = "总金额";

                // 填充数据
                for (int i = 0; i < orders.Count; i++)
                {
                    worksheet.Cells[i + 2, 1] = orders[i].AlbumId;
                    worksheet.Cells[i + 2, 2] = orders[i].TotalQuantity;
                    worksheet.Cells[i + 2, 3] = orders[i].TotalRevenue;
                }

                // 基本样式：表头加粗
                Excel.Range header = worksheet.Range["A1", "C1"];
                header.Font.Bold = true;

                // 自动调整列宽
                worksheet.Columns.AutoFit();

                // 使用唯一文件名避免冲突
                tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xlsx");

                // 保存文件
                _workbook.SaveAs(tempFile, Excel.XlFileFormat.xlOpenXMLWorkbook);

                // 显式关闭工作簿
                _workbook.Close(false);
                Marshal.ReleaseComObject(_workbook);
                _workbook = null;

                // 强制Excel释放资源
                _excelApp.Quit();
                Marshal.ReleaseComObject(_excelApp);
                _excelApp = null;

                // 等待资源释放
                GC.Collect();
                GC.WaitForPendingFinalizers();

                // 读取文件内容
                byte[] fileBytes;
                using (FileStream fs = new FileStream(tempFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    fileBytes = new byte[fs.Length];
                    fs.Read(fileBytes, 0, (int)fs.Length);
                }

                return fileBytes;
            }
            catch (Exception ex)
            {
                // 记录日志或处理异常
                throw new ApplicationException("导出Excel失败", ex);
            }
            finally
            {
                // 确保删除临时文件
                if (tempFile != null && File.Exists(tempFile))
                {
                    try
                    {
                        File.Delete(tempFile);
                    }
                    catch
                    {
                        // 忽略删除错误
                    }
                }

                // 确保资源释放
                Dispose();
            }
        }

        public void Dispose()
        {
            if (!_disposed)
            {
                try
                {
                    if (_workbook != null)
                    {
                        _workbook.Close(false);
                        Marshal.ReleaseComObject(_workbook);
                    }
                    if (_excelApp != null)
                    {
                        _excelApp.Quit();
                        Marshal.ReleaseComObject(_excelApp);
                    }
                }
                finally
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
                _disposed = true;
            }
        }
    }
}